﻿using Infrastructure.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Zj.OpenAuth.App.MenuApp;
using Zj.OpenAuth.DTO.Common;
using Zj.OpenAuth.Mvc.Models;

namespace Zj.OpenAuth.Mvc.Controllers
{
    public class MenusController : Controller
    {
        private IMenuAppService _service;

        public MenusController(IMenuAppService service)
        {
            this._service = service;
        }



        // GET: Departments
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult GetTreeData()
        {
            return Json(_service.GetAllList()
                .Select(d =>
            new TreeVm()
            {
                id = d.Id.ToString(),
                parent = d.ParentId == null ? "#" : d.ParentId.ToString(),
                text = d.Text
            }), JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetChildrenByParent(int? parentId, int startPage, int pageSize)
        {
            int rowCount = 0;
            var result = _service.GetChildrenByParent(parentId, startPage, out rowCount, pageSize);
            return Json(new
            {
                rowCount = rowCount,
                pageCount = Math.Ceiling(Convert.ToDecimal(rowCount) / pageSize),
                rows = result,
            }, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Get(int? id)
        {
            return Json(_service.Get(id.Value), JsonRequestBehavior.AllowGet);
        }



        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Save(MenuDTO dto)
        {
            if (!ModelState.IsValid)
            {
                return Json(new AjaxResult(DoResult.Failed, "保存失败"), JsonRequestBehavior.AllowGet);
            }
            if (_service.AddOrEdit(dto))
            {
                return Json(new AjaxResult(DoResult.Success, "保存成功"), JsonRequestBehavior.AllowGet);
            }
            return Json(new AjaxResult(DoResult.Failed, "保存失败"), JsonRequestBehavior.AllowGet);
        }


        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return Json(new AjaxResult(DoResult.Failed, "删除失败"), JsonRequestBehavior.AllowGet);
            }
            _service.Delete(id.Value);
            return Json(new AjaxResult(DoResult.Success, "删除成功"), JsonRequestBehavior.AllowGet);
        }


        public ActionResult DeleteMuti(string ids)
        {
            var idList = ids.Split(',').Select(s => Convert.ToInt32(s)).ToList();
            _service.DeleteMuti(idList);
            return Json(new AjaxResult(DoResult.Success, "删除成功"), JsonRequestBehavior.AllowGet);
        }
    }
}